import { _decorator, Button, Component, Node, director, EventHandler, Sprite, sys, UITransform, Widget } from 'cc';
import { createUILabel, createUINode, getFrameAsset, getSetting, showToast } from '../utils';
import { AudioMgr } from '../Runtime/AudioMgr';
import DataManager from '../Runtime/DataManager';
import { ControllerManager } from '../UI/ControllerManager';
import { setButton } from '../service/wx';
import { useSocket } from '../service/socket';
import { CommonElement } from '../UI/CommonElement';
import { userStore } from '../service/user';
import { GAME_MODE_ENUM } from '../../Enums';
import { getLevels } from '../api/game';
const { ccclass } = _decorator;
const socket = useSocket();
const wx = window['wx']
@ccclass('loginManager')
export class loginManager extends Component {
    actionList = [
        {
            label: "登 录 游 戏",
            handler: "loginGame",
        },
        {
            label: "试 玩 关 卡",
            handler: "trialLevels",
        },
    ]
    play_music: boolean
    controllerManager
    commonElement
    loginNode: Node
    loadingLevels: boolean = false
    level_list = []
    async start() {
        const loginNode = createUINode("loginNode")
        loginNode.setParent(this.node)
        this.loginNode = loginNode
        this.controllerManager = this.loginNode.addComponent(ControllerManager)
        this.controllerManager.init()
        DataManager.Instance.controllerManager = this.controllerManager
        await this.controllerManager.loadAssortAssets()
        this.commonElement = this.loginNode.addComponent(CommonElement)
        this.commonElement.setBackground()
        this.setActionButton()
        this.audioMute()
        if (DataManager.Instance.audioMgr == null) {
            DataManager.Instance.audioMgr = new AudioMgr()
        }
        if (!DataManager.Instance.mute) {
            DataManager.Instance.audioMgr.play(DataManager.Instance.audio.find(item => item.name == '1258_menu_music'))
            this.play_music = true
        }
        userStore().share()
    }
    // 设置操作按钮
    setActionButton() {
        if (this.node.getChildByName('action-button')) {
            this.node.getChildByName('action-button').destroy()
        }
        const action = createUINode("action-button")
        action.setParent(this.loginNode)
        let temp = true //是否显示本机的登录按钮
        if (getSetting() == 'wx') {
            const wx = window['wx']
            wx.getSetting({
                success(res) {
                    if (res.authSetting['scope.userInfo']) {
                        // 已经授权，可以直接调用 getUserInfo 获取头像昵称
                    } else {
                        let info = wx.getWindowInfo()
                        // 否则，先通过 wx.createUserInfoButton 接口发起授权
                        let button = wx.createUserInfoButton({
                            type: 'text',
                            text: ' ',
                            style: {
                                // backgroundColor: '#ff0000',
                                left: info.windowWidth / 2 - 100,
                                top: info.windowHeight / 2 - 40,
                                width: 200,
                                height: 50,
                                lineHeight: 50,
                                color: '#ffffff',
                                fontSize: 16,
                                textAlign: 'center'
                            }
                        })
                        setButton(button)
                        temp = false
                    }
                }
            })
        }
        this.actionList.forEach(async (item, index) => {
            const node = createUINode(item.label)
            node.setParent(action)
            const widget = node.addComponent(Widget)
            widget.isAlignTop = true
            widget.top = index * 100
            const transform = node.getComponent(UITransform)
            transform.setContentSize(250, 100)
            createUILabel({ parentNode: node, text: item.label, fontSize: 50, lineHeight: 50, color: "#D6D6D6" })
            if (!temp && index == 0) { } else {
                const button = node.addComponent(Button)
                const eventHandler = new EventHandler();
                eventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
                eventHandler.component = 'loginManager';// 这个是脚本类名
                eventHandler.handler = item.handler;
                button.clickEvents.push(eventHandler)
                button.duration = .1
                button.zoomScale = 0.95
                button.transition = Button.Transition.SCALE
            }
        })
    }
    // 静音/播放
    async audioMute() {
        const node = createUINode('audioMute')
        node.setParent(this.node)
        node.setSiblingIndex(99)
        const transform = node.getComponent(UITransform)
        transform.setContentSize(50, 50)
        const widget = node.addComponent(Widget)
        widget.isAlignTop = true
        widget.top = 50
        widget.isAlignRight = true
        if (sys.isMobile && typeof (wx) !== "undefined") {
            widget.right = 300
        } else {
            widget.right = 100
        }
        const sprite = node.addComponent(Sprite)
        sprite.sizeMode = Sprite.SizeMode.CUSTOM
        sprite.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, '821.png').spriteFrame //spriteFrame.find(item => item.name == "821")
        const button = node.addComponent(Button)
        button.duration = .1
        button.zoomScale = 0.95
        button.transition = Button.Transition.SCALE
        const eventHandler = new EventHandler();
        eventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
        eventHandler.component = 'loginManager';// 这个是脚本类名
        eventHandler.handler = 'changeAudio';
        button.clickEvents.push(eventHandler)

        const closeNode = createUINode("closeNode")
        closeNode.setParent(node)
        closeNode.active = false
        const closeTransform = closeNode.getComponent(UITransform)
        closeTransform.setContentSize(35, 35)
        const closeSprite = closeNode.addComponent(Sprite)
        closeSprite.sizeMode = Sprite.SizeMode.CUSTOM
        closeSprite.spriteFrame = getFrameAsset(DataManager.Instance.homeAssets, '493.png').spriteFrame// spriteFrame.find(item => item.name == '493')
        closeNode.active = DataManager.Instance.mute
    }
    // 静音/播放事件
    changeAudio() {
        if (DataManager.Instance.mute) {
            if (this.play_music) {
                DataManager.Instance.audioMgr.resume()
            } else {
                DataManager.Instance.audioMgr.play(DataManager.Instance.audio.find(item => item.name == '1258_menu_music'))
                this.play_music = true
            }
        } else {
            DataManager.Instance.audioMgr.pause()
        }
        DataManager.Instance.mute = !DataManager.Instance.mute
        sys.localStorage.setItem('mute', JSON.stringify(DataManager.Instance.mute))
        this.changeCloseButton("audioMute")
    }
    changeCloseButton(name) {
        let node = this.node.getChildByName(name)
        let closeNode = node.getChildByName("closeNode")
        closeNode.active = !closeNode.active
    }
    // 登录游戏
    loginGame() {
        // phone({ phone: "15847380321", smsCode: "123456" }).then(res => {
        //     userStore().setToken(res);
        //     showToast("登录成功")
        //     // userStore().get()
        //     // director.loadScene('home')
        // }).catch(err => {
        //     showToast(err.message)
        // })
        // return
        userStore().login().then(res => {
            // showToast("登录成功")
            socket.connect()
            setTimeout(() => {
                director.loadScene('home')
            }, 600)
        }).catch(err => { })
    }
    // 试玩关卡
    async trialLevels() {
        if (DataManager.Instance.drawerNumber != 0) {
            return
        }
        let { content } = await this.controllerManager.showDrawerContent({ name: 'gameType', tips: "模式选择" })
        this.commonElement.createPlayGame(content, "loginManager")
    }
    // 选择单/双人
    async selectPerson(event: Event, eventData: string) {
        if (this.loadingLevels) return
        if (eventData == 'doublePerson') {
            if (sys.isMobile) {
                let text = '仅支持pc端小游戏,手机状态下请等待后续联机模式...'
                await this.controllerManager.showDrawerText({ name: 'tips', label: "提示", text })
                return
            }
            this.commonElement.setDoublePersonStatus()
            this.commonElement.setSinglePersonStatus("#fbfbfd", false)
            DataManager.Instance.gameMode = GAME_MODE_ENUM.DOUBLE
        } else if (eventData == 'singlePerson') {

            this.commonElement.setDoublePersonStatus("#fbfbfd", false)
            this.commonElement.setSinglePersonStatus()
            DataManager.Instance.gameMode = GAME_MODE_ENUM.SINGLE
        }
        await this.loadLevels()
    }
    // 加载关卡
    async loadLevels() {
        this.loadingLevels = true
        return getLevels().then(async res => {
            this.level_list = res
            this.loadingLevels = false
            await this.commonElement.selectLevel(this.controllerManager, res, "loginManager")
        }).catch(res => {
            showToast(res.message)
            console.log(res)
        })
    }
    // 确定关卡
    async determineLevels(event: Event, eventData: string) {
        if (DataManager.Instance.disbledButton) {
            return
        }
        let index = this.level_list.findIndex(item => item.id == eventData)
        if (index == -1) {
            let text = '关卡信息出错,请联系开发人员'
            await this.controllerManager.showDrawerText({ text })
            return
        }
        if (this.level_list[index].levels.length == 0) {
            let text = '当前关卡未解锁,请通关上一关卡后继续'
            await this.controllerManager.showDrawerText({ text })
            DataManager.Instance.disbledButton = true
            return
        }
        DataManager.Instance.audioMgr.stop()
        await this.controllerManager.close('selectLevel')
        this.commonElement.setCreateRecord(this.level_list[index])
    }
    onDestroy() {
        DataManager.Instance.drawerNumber = 0
        DataManager.Instance.audioMgr.stop()
    }
}


